﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace LiMinCRMPlugin.InterfaceDocking
{
    /// <summary>
    /// 销售订单审核反审核插件
    /// </summary>
    /// <remarks>
    /// 功能：应收单在审核反审核时更新订单状态和计划跟踪号到CRM。
    /// 创建人：wzx
    /// 创建日期：2024.5.8
    /// 修改信息（1）：修改人，修改日期，修改内容
    /// </remarks>
    /// 
    [Description("销售订单审核反审核同步信息至CRM")]
    [HotUpdate]
    public class SaleOrderUpdateCRM : AbstractOperationServicePlugIn
    {

        //OnPreparePropertys 数据加载前，确保需要的属性被加载
        public override void OnPreparePropertys(PreparePropertysEventArgs e)
        {
            base.OnPreparePropertys(e);
            //单据状态
            e.FieldKeys.Add("FDocumentStatus");
            //预计发货日期
            e.FieldKeys.Add("F_RDLV_AntiShipmentDate");
            //计划跟踪号
            e.FieldKeys.Add("FMtoNo");
            //CRM明细内码
            e.FieldKeys.Add("F_DEV_CRMEntryId");
            //数据来源
            e.FieldKeys.Add("F_DEV_DataSrc");

            //创建人
            e.FieldKeys.Add("FCreatorId");
        }
        /// <summary>
        /// 事务结束后事件
        /// </summary>
        /// <param name="e"></param>
        public override void AfterExecuteOperationTransaction(AfterExecuteOperationTransaction e)
        {
            base.AfterExecuteOperationTransaction(e);
           
            //读取全部的单据,for循环,转换成DynamicObject类型
            foreach (DynamicObject entity in e.DataEntitys)
            {
                string UserAccount = "";//用户账号
                DynamicObject User = entity["CreatorId"] as DynamicObject;//用户
                if (User != null)
                {
                    UserAccount = Convert.ToString(User["UserAccount"]);
                }
                string FID = Convert.ToString(entity["Id"]);//订单内码
                string DocumentStatus = Convert.ToString(entity["DocumentStatus"]);//订单状态                                              
                string BillNo = entity["BillNo"].ToString();//订单编号
                string F_DEV_DataSrc = entity["F_DEV_DataSrc"].ToString();//数据来源
                DynamicObjectCollection FEntityDetail = entity["SaleOrderEntry"] as DynamicObjectCollection;//明细 
                if (F_DEV_DataSrc == "CRM")
                {
                    #region 销售订单mainTable数组
                    SaleOrderModel.mainTableList mainTable = new SaleOrderModel.mainTableList();
                    if (DocumentStatus == "C")
                    {
                        mainTable.ddzt = 2;
                    }
                    else if (DocumentStatus == "D")
                    {
                        mainTable.ddzt = 3;
                    }
                    mainTable.ddbh = BillNo;
                    mainTable.djnm = FID;

                    #endregion
                    List<SaleOrderModel.detailList> detailList = new List<SaleOrderModel.detailList>();//明细数据组
                    foreach (var item in FEntityDetail)
                    {
                        string FENTRTYID = Convert.ToString(item["id"]);
                        string AntiShipmentDate = Convert.ToString(item["F_RDLV_AntiShipmentDate"]);
                        string MtoNo = Convert.ToString(item["MtoNo"]);
                        string CRMEntryId = Convert.ToString(item["F_DEV_CRMEntryId"]);
                        #region 销售订单detail数组
                        SaleOrderModel.operate operate = new SaleOrderModel.operate();
                        operate.action = "SaveOrUpdate";

                        SaleOrderModel.dataList dataList = new SaleOrderModel.dataList();
                        dataList.sczlh = MtoNo;
                        if (this.FormOperation.Operation.ToUpper() == "AUDIT" || this.FormOperation.Operation.ToUpper() == "UPDATECRM"|| this.FormOperation.Operation.ToUpper() == "UNAUDIT")
                        {
                            dataList.id = CRMEntryId;
                        }
                        else if(this.FormOperation.Operation.ToUpper() == "DELETE")
                        {
                            dataList.id = "";
                        }

                        SaleOrderModel.detailList detailList1 = new SaleOrderModel.detailList();
                        detailList1.operate = operate;
                        detailList1.data = dataList;
                        detailList.Add(detailList1);
                        #endregion
                    }
                    if (this.FormOperation.Operation.ToUpper() == "AUDIT"|| this.FormOperation.Operation.ToUpper() == "UPDATECRM")
                    {
                        Return resultAdd = CRMUpdateSalesOrder(mainTable, detailList, UserAccount);
                        if (resultAdd.status == "1")
                        {
                            #region 销售订单写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                            Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                            interfaceLog.FBILLNO = BillNo;
                            interfaceLog.FBILLID = FID;
                            interfaceLog.FDATE = System.DateTime.Now;
                            interfaceLog.FINTERNAME = "更新销售订单";
                            interfaceLog.FInvokeType = "审核";
                            interfaceLog.Ftoken = "";
                            interfaceLog.FSTATUS = "成功";
                            interfaceLog.FRequsetData = "{\"data\":[{\"operationinfo\":{\"operator\":\"kd-jxy\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":" + JsonConvert.SerializeObject(mainTable) + ",\"detail1\":" + JsonConvert.SerializeObject(detailList) + "}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                            interfaceLog.FReturnData = JsonConvert.SerializeObject(resultAdd.datajson);
                            interfaceLog.FRequest = "{\"data\":[{\"operationinfo\":{\"operator\":\"kd-jxy\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":" + JsonConvert.SerializeObject(mainTable) + ",\"detail1\":" + JsonConvert.SerializeObject(detailList) + "}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                            interfaceLog.FReturn = JsonConvert.SerializeObject(resultAdd.datajson);
                            string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                            List<string> sqlList = new List<string>();
                            if (!string.IsNullOrEmpty(LogSql))
                            {
                                sqlList.Add(LogSql);
                            }
                            //更新单据
                            string updateSql = string.Format(@"/*dialect*/ update RDLV_t_BenchmarkPrice set F_RDLV_FDATE='{0}',F_RDLV_FSTATUS='{1}' 
                    where FID={2}", interfaceLog.FDATE, interfaceLog.FSTATUS, FID);
                            sqlList.Add(updateSql);
                            DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                            #endregion
                        }
                        else
                        {
                            #region 销售订单写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                            Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                            interfaceLog.FBILLNO = BillNo;
                            interfaceLog.FBILLID = FID;
                            interfaceLog.FDATE = System.DateTime.Now;
                            interfaceLog.FINTERNAME = "更新销售订单";
                            interfaceLog.FInvokeType = "审核";
                            interfaceLog.Ftoken = "";
                            interfaceLog.FSTATUS = "失败";
                            interfaceLog.FRequsetData = "{\"data\":[{\"operationinfo\":{\"operator\":\"kd-jxy\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":" + JsonConvert.SerializeObject(mainTable) + ",\"detail1\":" + JsonConvert.SerializeObject(detailList) + "}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                            interfaceLog.FReturnData = JsonConvert.SerializeObject(resultAdd.datajson);
                            interfaceLog.FRequest = "{\"data\":[{\"operationinfo\":{\"operator\":\"kd-jxy\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":" + JsonConvert.SerializeObject(mainTable) + ",\"detail1\":" + JsonConvert.SerializeObject(detailList) + "}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                            interfaceLog.FReturn = JsonConvert.SerializeObject(resultAdd.datajson);
                            string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                            List<string> sqlList = new List<string>();
                            if (!string.IsNullOrEmpty(LogSql))
                            {
                                sqlList.Add(LogSql);
                            }
                            //更新单据
                            string updateSql = string.Format(@"/*dialect*/ update RDLV_t_BenchmarkPrice set F_RDLV_FDATE='{0}',F_RDLV_FSTATUS='{1}' 
                    where FID={2}", interfaceLog.FDATE, interfaceLog.FSTATUS, FID);
                            sqlList.Add(updateSql);
                            DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                            #endregion
                        }
                    }
                    else if (this.FormOperation.Operation.ToUpper() == "UNAUDIT")
                    {
                        Return resultAdd = CRMUpdateSalesOrder(mainTable, detailList, UserAccount);
                        if (resultAdd.status == "1")
                        {
                            #region 销售订单写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                            Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                            interfaceLog.FBILLNO = BillNo;
                            interfaceLog.FBILLID = FID;
                            interfaceLog.FDATE = System.DateTime.Now;
                            interfaceLog.FINTERNAME = "更新销售订单";
                            interfaceLog.FInvokeType = "反审核";
                            interfaceLog.Ftoken = "";
                            interfaceLog.FSTATUS = "成功";
                            interfaceLog.FRequsetData = "{\"data\":[{\"operationinfo\":{\"operator\":\"kd-jxy\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":" + JsonConvert.SerializeObject(mainTable) + ",\"detail1\":" + JsonConvert.SerializeObject(detailList) + "}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                            interfaceLog.FReturnData = JsonConvert.SerializeObject(resultAdd.datajson);
                            interfaceLog.FRequest = "{\"data\":[{\"operationinfo\":{\"operator\":\"kd-jxy\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":" + JsonConvert.SerializeObject(mainTable) + ",\"detail1\":" + JsonConvert.SerializeObject(detailList) + "}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                            interfaceLog.FReturn = JsonConvert.SerializeObject(resultAdd.datajson);
                            string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                            List<string> sqlList = new List<string>();
                            if (!string.IsNullOrEmpty(LogSql))
                            {
                                sqlList.Add(LogSql);
                            }
                            //更新单据
                            string updateSql = string.Format(@"/*dialect*/ update RDLV_t_BenchmarkPrice set F_RDLV_FDATE='{0}',F_RDLV_FSTATUS='{1}' 
                    where FID={2}", interfaceLog.FDATE, interfaceLog.FSTATUS, FID);
                            sqlList.Add(updateSql);
                            DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                            #endregion
                        }
                        else
                        {
                            #region 销售订单写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                            Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                            interfaceLog.FBILLNO = BillNo;
                            interfaceLog.FBILLID = FID;
                            interfaceLog.FDATE = System.DateTime.Now;
                            interfaceLog.FINTERNAME = "更新销售订单";
                            interfaceLog.FInvokeType = "反审核";
                            interfaceLog.Ftoken = "";
                            interfaceLog.FSTATUS = "失败";
                            interfaceLog.FRequsetData = "{\"data\":[{\"operationinfo\":{\"operator\":\"kd-jxy\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":" + JsonConvert.SerializeObject(mainTable) + ",\"detail1\":" + JsonConvert.SerializeObject(detailList) + "}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                            interfaceLog.FReturnData = JsonConvert.SerializeObject(resultAdd.datajson);
                            interfaceLog.FRequest = "{\"data\":[{\"operationinfo\":{\"operator\":\"kd-jxy\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":" + JsonConvert.SerializeObject(mainTable) + ",\"detail1\":" + JsonConvert.SerializeObject(detailList) + "}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                            interfaceLog.FReturn = JsonConvert.SerializeObject(resultAdd.datajson);
                            string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                            List<string> sqlList = new List<string>();
                            if (!string.IsNullOrEmpty(LogSql))
                            {
                                sqlList.Add(LogSql);
                            }
                            //更新单据
                            string updateSql = string.Format(@"/*dialect*/ update RDLV_t_BenchmarkPrice set F_RDLV_FDATE='{0}',F_RDLV_FSTATUS='{1}' 
                    where FID={2}", interfaceLog.FDATE, interfaceLog.FSTATUS, FID);
                            sqlList.Add(updateSql);
                            DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                            #endregion
                        }

                    }
                    else if (this.FormOperation.Operation.ToUpper() == "DELETE")
                    {
                        mainTable.djnm = "";
                        Return resultAdd = CRMUpdateSalesOrder(mainTable, detailList, UserAccount);
                        if (resultAdd.status == "1")
                        {
                            #region 销售订单写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                            Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                            interfaceLog.FBILLNO = BillNo;
                            interfaceLog.FBILLID = FID;
                            interfaceLog.FDATE = System.DateTime.Now;
                            interfaceLog.FINTERNAME = "更新销售订单";
                            interfaceLog.FInvokeType = "删除";
                            interfaceLog.Ftoken = "";
                            interfaceLog.FSTATUS = "成功";
                            interfaceLog.FRequsetData = "{\"data\":[{\"operationinfo\":{\"operator\":\"kd-jxy\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":" + JsonConvert.SerializeObject(mainTable) + ",\"detail1\":" + JsonConvert.SerializeObject(detailList) + "}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                            interfaceLog.FReturnData = JsonConvert.SerializeObject(resultAdd.datajson);
                            interfaceLog.FRequest = "{\"data\":[{\"operationinfo\":{\"operator\":\"kd-jxy\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":" + JsonConvert.SerializeObject(mainTable) + ",\"detail1\":" + JsonConvert.SerializeObject(detailList) + "}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                            interfaceLog.FReturn = JsonConvert.SerializeObject(resultAdd.datajson);
                            string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                            List<string> sqlList = new List<string>();
                            if (!string.IsNullOrEmpty(LogSql))
                            {
                                sqlList.Add(LogSql);
                            }
                            //更新单据
                            string updateSql = string.Format(@"/*dialect*/ update RDLV_t_BenchmarkPrice set F_RDLV_FDATE='{0}',F_RDLV_FSTATUS='{1}' 
                    where FID={2}", interfaceLog.FDATE, interfaceLog.FSTATUS, FID);
                            sqlList.Add(updateSql);
                            DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                            #endregion
                        }
                        else
                        {
                            #region 销售订单写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                            Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                            interfaceLog.FBILLNO = BillNo;
                            interfaceLog.FBILLID = FID;
                            interfaceLog.FDATE = System.DateTime.Now;
                            interfaceLog.FINTERNAME = "更新销售订单";
                            interfaceLog.FInvokeType = "删除";
                            interfaceLog.Ftoken = "";
                            interfaceLog.FSTATUS = "失败";
                            interfaceLog.FRequsetData = "{\"data\":[{\"operationinfo\":{\"operator\":\"kd-jxy\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":" + JsonConvert.SerializeObject(mainTable) + ",\"detail1\":" + JsonConvert.SerializeObject(detailList) + "}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                            interfaceLog.FReturnData = JsonConvert.SerializeObject(resultAdd.datajson);
                            interfaceLog.FRequest = "{\"data\":[{\"operationinfo\":{\"operator\":\"kd-jxy\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":" + JsonConvert.SerializeObject(mainTable) + ",\"detail1\":" + JsonConvert.SerializeObject(detailList) + "}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                            interfaceLog.FReturn = JsonConvert.SerializeObject(resultAdd.datajson);
                            string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                            List<string> sqlList = new List<string>();
                            if (!string.IsNullOrEmpty(LogSql))
                            {
                                sqlList.Add(LogSql);
                            }
                            //更新单据
                            string updateSql = string.Format(@"/*dialect*/ update RDLV_t_BenchmarkPrice set F_RDLV_FDATE='{0}',F_RDLV_FSTATUS='{1}' 
                    where FID={2}", interfaceLog.FDATE, interfaceLog.FSTATUS, FID);
                            sqlList.Add(updateSql);
                            DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                            #endregion
                        }

                    }
                }
            }
        }

        /// <summary>
        /// api配置
        /// </summary>
        public DataTable APISetting( string InterfaceName)
        {
            string Sql = string.Format(@"select * from RDLV_t_CRMInterface where F_RDLV_InterfaceName='{0}'", InterfaceName);
            return DBServiceHelper.ExecuteDataSet(this.Context, Sql).Tables[0];
        }



        /// <summary>
        /// CRM更新销售订单接口
        /// </summary>
        public Return CRMUpdateSalesOrder(SaleOrderModel.mainTableList mainTable, List<SaleOrderModel.detailList> detail1,string UserAccount)
        {
            //当前日期
            String currentDate = DateTime.Now.ToString("yyyy-MM-dd");
            //当前时间
            String currentTime = DateTime.Now.ToString("hh:mm:ss");

            string requestUri1 = "http://10.10.17.127:8086/api/cube/restful/interface/saveOrUpdateModeData/update_order_delivery_date";

            //系统标识
            String systemid = "kingdee";
            //密码
            String d_password = "p@ssw0rd...";
            DataTable dt = APISetting("更新销售订单");
            if (dt.Rows.Count > 0)
            {
                requestUri1 = Convert.ToString(dt.Rows[0]["F_RDLV_URL"]);
                systemid = Convert.ToString(dt.Rows[0]["F_RDLV_SystemId"]);
                d_password = Convert.ToString(dt.Rows[0]["F_RDLV_Password"]);
            }
            //获取时间戳
            String currentTimeTamp = getTimestamp();
            String md5Source = systemid + d_password + currentTimeTamp;
            String md5OfStr = Md5(md5Source).ToLower();

            Return result = PostToUpdateNews(requestUri1, systemid, currentTimeTamp, md5OfStr, mainTable, detail1,UserAccount);


            return result;
        }



        /// <summary>
        /// md5加密
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static String Md5(string s)
        {
            char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(s);
            byte[] result = md5.ComputeHash(inputBytes);
            int j = result.Length;
            char[] str = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++)
            {
                byte byte0 = result[i];
                str[k++] = hexDigits[byte0 >> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        }






        /// <summary>
        /// CRM更新销售订单OST
        /// </summary>
        public static Return PostToUpdateNews(string url, string systemid, string currentTimeTamp, string md5OfStr, SaleOrderModel.mainTableList mainTable, List<SaleOrderModel.detailList> detail1, string UserAccount)
        {

            Dictionary<string, string> dic = new Dictionary<string, string>
            {
                {"datajson","{\"data\":[{\"operationinfo\":{\"operator\":\""+UserAccount+"\",\"operationDate\":\""+DateTime.Now.ToString("yyyy-MM-dd")+"\",\"operationTime\":\""+DateTime.Now.ToString("HH:mm:ss")+"\"},\"mainTable\":"+JsonConvert.SerializeObject(mainTable)+",\"detail1\":"+JsonConvert.SerializeObject(detail1)+"}],\"header\":{\"systemid\":\""+systemid+"\",\"currentDateTime\":\""+currentTimeTamp+"\",\"Md5\":\""+md5OfStr+"\"}}"}
            };
            string result = string.Empty;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
            #region 添加Post 参数
            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in dic)
            {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }
            string b = builder.ToString();
            byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            Return @return = new Return();
            result = Regex.Unescape(result);//去除转义符
            result = Regex.Unescape(result);//去除转义符
            string[] resAry = result.Split(new string[] { "status" }, StringSplitOptions.None);
            string[] json = result.Split(new string[] { "datajson" }, StringSplitOptions.None);
            string status = "";
            status = resAry[resAry.Length - 1].Replace("\"", "");
            status = status.Replace(":", "");
            status = status.Replace("}", "");
            string json1 = json[json.Length - 1].Remove(0, 3);
            json1 = Regex.Replace(json1, "\"\"", "\"");
            json1 = Regex.Unescape(json1);
            //}
            @return.status = status;
            @return.datajson = json1;
            return @return;
        }


        /**
       * 获取时间戳   格式如：19990101235959
       * @return
       */
        public static String getTimestamp()
        {

            return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss").Replace("-", "").Replace(":", "").Replace(" ", "").Replace("/", "");
        }

        /**
          * 接口返回值自定义 
          */
        public class Return
        {
            public string status { get; set; }
            public string datajson { get; set; }
        }
    }
 
}
